﻿package com.reyco1.manager
{
    import flash.events.*;
    import flash.net.FileReference;
    import flash.net.URLRequest;
    import com.reyco1.util.MathUtil;
    import com.reyco1.extension.DispatchExtension;
    import com.reyco1.events.FileEvent;
    import flash.events.IOErrorEvent;
   
    public class DownloadManager extends DispatchExtension
	{
        /*
        variables
        */
        private var DOWNLOAD_URL:String;
        private var objFileReference:FileReference;

		/*
		constructor
		*/
        public function DownloadManager() 
        {
        	this.init();
        }

        /**
         * Add listeners to the File Reference Object.
         */
        private function init():void 
        {
            this.objFileReference = new FileReference();
            this.objFileReference.addEventListener(Event.OPEN, this.openHandler);
            this.objFileReference.addEventListener(ProgressEvent.PROGRESS, this.progressHandler);
            this.objFileReference.addEventListener(Event.COMPLETE, this.completeHandler);
            this.objFileReference.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }

        /**
         * Cancel the current download.
         * 
         */       
        public function cancelDownload():void 
        {
            this.objFileReference.cancel();
        }

        /**
         * Begin downloading the specified file 
         * @param $strFileToDownload : File to download
         * 
         */        
        public function startDownload($strFileToDownload:String):void 
        {
        	DOWNLOAD_URL = $strFileToDownload;
            var request:URLRequest = new URLRequest();
            request.url = DOWNLOAD_URL;
            this.objFileReference.download(request);
            this.dispatchEvent(new FileEvent(FileEvent.DOWNLOAD_START, {file:DOWNLOAD_URL}));
        }

        private function openHandler(event:Event):void 
        {

        }
        
        private function progressHandler(event:ProgressEvent):void 
        {
        	var percent:Number = MathUtil.percentage(event.bytesLoaded, event.bytesTotal);
            this.dispatchEvent(new FileEvent(FileEvent.DOWNLOAD_PROGRESS, {percent:percent}));
        }

        private function completeHandler(event:Event):void 
        {
        	this.dispatchEvent(new FileEvent(FileEvent.DOWNLOAD_COMPLETE, {}));
        }
        
        private function ioErrorHandler(event:IOErrorEvent):void 
		{
            this.dispatchEvent(new FileEvent(FileEvent.DOWNLOAD_ERROR, {}));
        }
    }
}